package com.cy.teducommunitys.com.common.config;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import lombok.Data;

@Configuration
@ConfigurationProperties("executor")  //读取配置文件中前缀是executor的配置，并赋值给属性（调用属性的set方法）
@Data
public class SpringExecutorConfig implements AsyncConfigurer{		
	private int corePoolSize = 10;	
	private int maximumPoolSize = 15;
	private long keepAliveTime = 30;
	private BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<>(10);
	private ThreadFactory threadFactory = new ThreadFactory() {		
		private AtomicLong atomicLong = new AtomicLong();
		@Override
		public Thread newThread(Runnable r) {
			return new Thread(r,"async-thread-"+atomicLong.getAndIncrement());
		}
	};
	
	@Bean("asyncThreadPool")
	public ThreadPoolExecutor newThreadPoolExecutor() {		 
		return new ThreadPoolExecutor(
				corePoolSize, 
				maximumPoolSize, 
				keepAliveTime, 
				TimeUnit.SECONDS, 
				workQueue, 
				threadFactory);
	}
	
	@Override
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
		pool.setCorePoolSize(corePoolSize);
		pool.setMaxPoolSize(maximumPoolSize);
		pool.setKeepAliveSeconds(30);
		pool.setQueueCapacity(10);
		pool.initialize();
		return pool;
	}

}
